package com.xci.platform.controller;

import com.xci.platform.core.BoolMessage;
import com.xci.platform.helper.DateHelper;
import com.xci.platform.helper.StringHelper;
import com.xci.platform.upload.IUploadFile;
import com.xci.platform.upload.UploadFileInfo;
import com.xci.platform.upload.UploadFileOptions;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/editormd")
public class EditorMdFileController {

    /**
     * 文件上传
     */
    @Resource
    private IUploadFile uploadFile;

    @ResponseBody
    @PostMapping("/upload")
    public Object upload(HttpServletRequest request) {
        MultiValueMap<String, MultipartFile> multipartFiles =
                ((StandardMultipartHttpServletRequest) request).getMultiFileMap();

        String dirName = request.getParameter("dir");
        if (StringHelper.isBlank(dirName)) {
            dirName = "image";
        }

        String finalDirName = dirName;
        if (Arrays.stream(new String[]{"image", "flash", "media", "file"}).noneMatch(p -> p.toLowerCase().equals(finalDirName))) {
            return new BoolMessage<>(false, "目录名不正确");
        }
        UploadFileOptions options = new UploadFileOptions();
        //文件保存目录路径
        String rootDir = "/upload/editormd/";
        options.setUploadPath(StringHelper.format(rootDir + "{}/{}/", dirName, DateHelper.formatDate(new Date(), "yyyyMMdd")));
        options.setAllowMaxSize(1024 * 50);//50M
        options.setAllowExtension(new String[]{"gif", "jpg", "jpeg", "png", "bmp", "swf", "flv", "mp3", "mp4", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb", "zip", "rar", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "gz", "bz2"});

        BoolMessage<UploadFileInfo> result = new BoolMessage<>(false, "请指定上传的文件");
        for (List<MultipartFile> multipartFilex : multipartFiles.values()) {
            for (MultipartFile multipartFile : multipartFilex) {
                result = uploadFile.upload(multipartFile, options);
            }
        }

        Map<String, Object> obj = new HashMap<>();
        if (result.isSuccess()) {
            obj.put("success", 1);
            obj.put("message", "上传成功！");
            obj.put("url", request.getContextPath() + result.getData().getVirtualUrl());
        } else {
            obj.put("success", 0);
            obj.put("message", result.getMsg());
        }
        return obj;
    }
}
